#include "HumitureSensor.h"

#include <iostream>
#include <cjson/cJSON.h>
#include <wiringPi.h>
//#include "Buffer.h"


HumitureSensor::HumitureSensor(int deviceID, int pin, std::string dbName, std::string dataTbName, std::string confTbName)
	:Sensor(deviceID,dbName,dataTbName, confTbName),pin(pin)
{
	
}

HumitureSensor::~HumitureSensor()
{

}


SensorConfig HumitureSensor::readConfigFromBuffer()
{
	string configJson;
	SensorConfig config;
	if (buffer.readConfigJsonFromBuffer(configJson))
	{
		cout << "读取配置失败使用默认配置: sample = 1 \n";
		config.setSample(1);
		writeConfigToBuffer(config);
	}
	cJSON* configJsonObj = cJSON_Parse(configJson.c_str());
	cJSON* sample = cJSON_GetObjectItemCaseSensitive(configJsonObj, "sample");
	if (sample)
	{
		config.setSample(sample->valueint);
		cJSON_free(configJsonObj);
		cJSON_free(sample);
	}
		
	return config;
}

void HumitureSensor::writeConfigToBuffer(SensorConfig config)
{
	cJSON* configObj = cJSON_CreateObject();
	cJSON* sample = cJSON_CreateNumber(config.getSample());
	cJSON_AddItemToObject(configObj, "sample", sample);

	this->buffer.writeConfigJsonToBuffer(cJSON_Print(configObj));

	cJSON_free(configObj);
	cJSON_free(sample);
}

void HumitureSensor::recordSensorData()
{
	cJSON* humitureObj = cJSON_CreateObject();
	cJSON* temp = cJSON_CreateNumber(this->temperature);
	cJSON* humi = cJSON_CreateNumber(this->humidity);
	//cJSON* date = cJSON_CreateString(this->buffer.getCurrentTime().c_str());
	
	cJSON_AddItemToObject(humitureObj, "temperature", temp);
	cJSON_AddItemToObject(humitureObj, "humidity", humi);
	//cJSON_AddItemToObject(humitureObj, "date", date);

	buffer.writeDataJsonToBuffer(cJSON_Print(humitureObj));

	cJSON_free(humitureObj);
	cJSON_free(temp);
	cJSON_free(humi);
}

void HumitureSensor::readSensorData()
{
	unsigned char t, i, j;
	t = i = j = 0;
	unsigned char buf[5] = { 0, 0, 0, 0, 0 };
	
	pinMode(pin, OUTPUT); //SET OUTPUT
	pullUpDnControl(pin, PUD_UP);
	digitalWrite(pin, 0); //Data=0
	delay(20);			   //Pull down Least 18ms
	digitalWrite(pin, 1); //Data =1
	delayMicroseconds(30); //Pull up 20~40us
	pinMode(pin, INPUT);  //SET INPUT

	while (digitalRead(pin) && t < 100) //DHT11 Pull down 80us
	{
		t++;
		delayMicroseconds(1);
	};
	if (t >= 100)
		return ;
	t = 0;
	while (!digitalRead(pin) && t < 100) //DHT11 Pull up 80us
	{
		t++;
		delayMicroseconds(1);
	};
	if (t >= 100)
		return ;
	for (i = 0; i < 5; i++)
	{
		buf[i] = 0;
		for (j = 0; j < 8; j++)
		{
			buf[i] <<= 1;
			t = 0;
			while (digitalRead(pin) && t < 100)
			{
				t++;
				delayMicroseconds(1);
			}
			if (t >= 100)
				return ;
			t = 0;
			while (!digitalRead(pin) && t < 100)
			{
				t++;
				delayMicroseconds(1);
			}
			if (t >= 100)
				return ;
			delayMicroseconds(40);
			if (digitalRead(pin))
				buf[i] += 1;
		}
	}
	if (buf[0] + buf[1] + buf[2] + buf[3] != buf[4])
		return ;
	humidity = buf[0] + buf[1] * 0.1;
	temperature = buf[2] + buf[3] * 0.1;
}
